﻿namespace OboutInc
{
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class CallbackPanelContent : Panel
    {
        private CallbackPanel container;

        public CallbackPanelContent(CallbackPanel container)
        {
            if (container == null)
            {
                throw new Exception("Control cannot be placed inside a null CallbackPanel.");
            }
            this.container = container;
        }

        private IAJAX GetContainerPage()
        {
            IAJAX page = null;
            try
            {
                page = (IAJAX) this.container.Page;
            }
            catch (InvalidCastException)
            {
            }
            if (page == null)
            {
                page = (IAJAX) this.container.Page;
            }
            return page;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.container.DesignMode)
            {
                base.Render(writer);
            }
            else
            {
                if (!(this.container.Page is oboutAJAXPage))
                {
                    throw new Exception("CallbackPanel can only be placed inside an Obout AJAX page. Make sure your page inherits oboutAJAXPage.");
                }
                IAJAX containerPage = this.GetContainerPage();
                this.ID = (((this.container.ID == null) || this.container.ID.Equals(string.Empty)) ? this.container.ClientID : this.container.ID) + "_Content";
                if (containerPage.IsCallback)
                {
                    this.RenderContents(writer);
                }
                else
                {
                    writer.Write("<div ");
                    base.Attributes.Add("id", this.ID);
                    base.Attributes.Render(writer);
                    writer.Write(">");
                    base.RenderContents(writer);
                    writer.Write("</div>");
                }
            }
        }

        internal void RenderEmpty(HtmlTextWriter writer)
        {
            if (this.container.DesignMode)
            {
                base.Render(writer);
            }
            else
            {
                if (!(this.container.Page is oboutAJAXPage) && !this.container.DesignMode)
                {
                    throw new Exception("CallbackPanelLoading can only be placed inside a CallbackPanel.");
                }
                this.ID = (((this.container.ID == null) || this.container.ID.Equals(string.Empty)) ? this.container.ClientID : this.container.ID) + "_Content";
                writer.Write("<div ");
                base.Attributes.Add("id", this.ID);
                base.Attributes.Render(writer);
                writer.Write(">");
                writer.Write("</div>");
            }
        }
    }
}

